package com.atguigu.gulimall.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.gulimallsearch.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.gulimallsearch.constant.EsConstant;
import com.atguigu.gulimall.gulimallsearch.feign.ProductFrignService;
import com.atguigu.gulimall.gulimallsearch.service.MallSearchService;
import com.atguigu.gulimall.gulimallsearch.vo.AttrResponseVo;
import com.atguigu.gulimall.gulimallsearch.vo.BrandVo;
import com.atguigu.gulimall.gulimallsearch.vo.SearchParam;
import com.atguigu.gulimall.gulimallsearch.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ProductFrignService frignService;
    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchResult result = null;
        // 1.准备检索请求
        SearchRequest searchRequest = buildSearchRequrest(searchParam);
        try {
            // 2.执行检索请求
            SearchResponse response = restHighLevelClient.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

            // 3.分析响应数据
           result= buildSearchResult(response,searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    //准备检索请求
    private SearchRequest buildSearchRequrest(SearchParam searchParam) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//构建dsl语句

        // 1. 模糊匹配 过滤(按照属性、分类、品牌、价格区间、库存) 先构建一个布尔Query

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 1.1 must-模糊匹配
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
        // 1.2 bool - filter Catalog3Id
        if (searchParam.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalog3Id", searchParam.getCatalog3Id()));
        }
        // 1.2 bool - brandId [集合]
        if (searchParam.getBrandId()!=null&&searchParam.getBrandId().size()>0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        // 属性查询
        if (searchParam.getAttrs()!=null&&searchParam.getAttrs().size()>0){

            for (String attrstr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();
                String[] s = attrstr.split("_");
                String Attrid=s[0];//检索属性id
                String[] attrValue = s[1].split(":");//检索属性值
                nestedBoolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId",Attrid));
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",attrValue));
                //每一个都必须生成一个nested查询
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", nestedBoolQueryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            }

        }

        // 1.2 bool - filter [库存]
        if (searchParam.getHasStock()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",searchParam.getHasStock()==1));
        }


        // 1.2 bool - filter [价格区间]
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())){
            //1_500/_500/500
            RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");
            String[] s = searchParam.getSkuPrice().split("_");
            if (s.length==2){
                skuPrice.gte(s[0]).lte(s[1]);
            } else if (s.length==1) {
                if (searchParam.getSkuPrice().startsWith("_")){
                    skuPrice.lte(s[0]);
                }
                if (searchParam.getSkuPrice().endsWith("_")){
                    skuPrice.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(skuPrice);
        }
        // 把以前所有条件都拿来进行封装
        searchSourceBuilder.query(boolQueryBuilder);

        //排序
        if (!StringUtils.isEmpty(searchParam.getSort())){
            String sort = searchParam.getSort();
            String[] s = sort.split("_");
            SortOrder order=s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(s[0], order);
        }
        //分页-----(n-1)*size
        searchSourceBuilder.from((searchParam.getPageNum()-1)*EsConstant.PRODUCT_SIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_SIZE);

        //高亮
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");//在前面加
            highlightBuilder.postTags("</b>");//后面加
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        //聚合分析
            //品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId");
        brandAgg.size(50);
                //品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brandAgg);
        //分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalog3Id").size(50);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalogAgg);
        //属性聚合
        NestedAggregationBuilder nestedAggregationBuilder = AggregationBuilders.nested("attr_agg", "attrs");
        // 3.1 聚合出当前所有的attrId
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        // 3.1.1 聚合分析出当前attrId对应的attrName
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        // 3.1.2 聚合分析出当前attrId对应的所有可能的属性值attrValue	这里的属性值可能会有很多 所以写50
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        //181----11.57
        // 3.2 将这个子聚合加入嵌入式聚合
        nestedAggregationBuilder.subAggregation(attrIdAgg);
        searchSourceBuilder.aggregation(nestedAggregationBuilder);
        String string = searchSourceBuilder.toString();
        System.out.println("----------------------构建的dsl"+string);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},searchSourceBuilder);
        return searchRequest;
    }
    //构建结果数据
    private SearchResult buildSearchResult(SearchResponse response ,SearchParam searchParam) {

        SearchResult result = new SearchResult();
        //        //查询到的所有商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels =new ArrayList<>();
        if (hits.getHits()!=null && hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {
                //获取所有数据
                String sourceAsString = hit.getSourceAsString();//数据中的source
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);//将字符串转换为对象
                if (!StringUtils.isEmpty(searchParam.getKeyword())){
                HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                String HighlightField = skuTitle.getFragments()[0].string();
                skuEsModel.setSkuTitle(HighlightField);


                }
                esModels.add(skuEsModel);
            }
        }

        result.setProduct(esModels);

//        //当前所有商品所有属性信息
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attrAgg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //获取属性id
            long id = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(id);
            //获取属性名
            String attrNameAgg = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrNameAgg);
            //获取属性值
            List<String> attr_value_agg = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
           attrVo.setAttrValue(attr_value_agg);

            attrVos.add(attrVo);
        }
         result.setAttrVos(attrVos);

//        //当前所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");//获取品牌聚合信息
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();//创建对象
            //获取品牌id
            Long keyAsString = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(keyAsString);//设置品牌id
            //得到品牌的图片
            String brand_img_agg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brand_img_agg);
            //得到品牌的名字
            String name_agg = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(name_agg);
            //把id和名字添加到集合中
            brandVos.add(brandVo);//添加到集合中
        }
        result.setBrandVos(brandVos);

//        //当前所有分类信息
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos=new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();//创建对象
            //得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));//设置分类id
            //获取分类名
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");//嵌套聚合
            String catalog_name = catalogNameAgg.getBuckets().get(0).getKeyAsString();//得到分类名
            catalogVo.setCatalogName(catalog_name);
            //把id和名字添加到集合中
            catalogVos.add(catalogVo);//添加到集合中
        }
        result.setCatalogVos(catalogVos);
//        ============以上从聚合信息获取=================
        //分页信息-总记录数
        long value = hits.getTotalHits().value;
        result.setTotal(value);
//        //分页信息-当前页码
        result.setPageNum(searchParam.getPageNum());
//        //分页信息-总页码
        int productSize = (int) (value%EsConstant.PRODUCT_SIZE==0?value/EsConstant.PRODUCT_SIZE:value/EsConstant.PRODUCT_SIZE+1);
        result.setTotalPages(productSize);
//
        List<Integer> pageNavs=new ArrayList<>();

        for (int i=1;i<=productSize;i++){
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //构建面包屑导航功能
        if (searchParam.getAttrs()!=null){
            List<SearchResult.navVo> collect = searchParam.getAttrs().stream().map(attr -> {
            //分析每个attr
            SearchResult.navVo navVo = new SearchResult.navVo();
            String[] s = attr.split("_");
            navVo.setNavValue(s[1]);
            R attrInfo = frignService.getAttrInfo(Long.parseLong(s[0]));
            result.getAttrIds().add(Long.parseLong(s[0]));
            if (attrInfo.getCode()==0){
                AttrResponseVo data = attrInfo.getData("attr", new TypeReference<AttrResponseVo>() {
                });
                String attrName = data.getAttrName();
                navVo.setNavName(attrName);
            }else {
                navVo.setNavName(s[0]);
            }
            String replace = getString(searchParam, attr,"attrs");//获取替换后的字符串
            navVo.setLink("http://search.gulimall.com/list.html?" + replace);
            //取消面包屑以后,我们要跳转到哪个地方,将请求url里面的当前制空,
            return navVo;
        }).collect(Collectors.toList());


            result.setNavs(collect);
        }

        // 检查searchParam对象中是否包含非空的品牌ID列表
        if(searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0){
            List<SearchResult.navVo> navs = result.getNavs();
            SearchResult.navVo navVo = new SearchResult.navVo();
            navVo.setNavName("品牌");
            // TODO 远程查询所有品牌
            R r = frignService.info(searchParam.getBrandId());
            if(r.getCode() == 0){
                List<BrandVo> brand = r.getData("brand", new TypeReference<List<BrandVo>>() {});
                StringBuffer buffer = new StringBuffer();
                // 替换所有品牌ID
                String replace = "";
                for (BrandVo brandVo : brand) {
                    buffer.append(brandVo.getName() + ";");
                    replace = getString(searchParam, brandVo.getBrandId() + "", "brandId");
                }
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
            }
            navs.add(navVo);
        }

        return result;
    }

    private static String getString(SearchParam searchParam, String value,String key) {
        String attrs =null;
        try {
            attrs= URLEncoder.encode(value, "UTF-8");
            attrs=attrs.replace("+","%20");//
            attrs = attrs.replace("%28", "(").replace("%29",")");
        } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
        }
        String replace = searchParam.get_queryString().replace("&"+key+"=" + attrs, "");
        return replace;
    }


}
